import { useState, useEffect, useCallback } from 'react'
import Taro from '@tarojs/taro'

// 环境检测
const isDev = process.env.NODE_ENV === 'development'
const log = isDev ? console.log : () => {}

// 防抖Hook
export const useDebounce = (value, delay = 300) => {
  const [debouncedValue, setDebouncedValue] = useState(value)
  
  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value)
    }, delay)
    
    return () => clearTimeout(handler)
  }, [value, delay])
  
  return debouncedValue
}

// 下拉刷新Hook
export const usePullToRefresh = (onRefresh, options = {}) => {
  const [refreshing, setRefreshing] = useState(false)
  const [lastRefreshTime, setLastRefreshTime] = useState(null)
  
  const {
    minInterval = 1000, // 最小刷新间隔（毫秒）
    threshold = 80 // 下拉阈值
  } = options
  
  const handleRefresh = useCallback(async () => {
    const now = Date.now()
    
    // 检查刷新间隔
    if (lastRefreshTime && now - lastRefreshTime < minInterval) {
      log('刷新间隔太短，跳过')
      return
    }
    
    try {
      setRefreshing(true)
      setLastRefreshTime(now)
      
      await onRefresh()
      
      // 显示刷新成功提示
      Taro.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 1500
      })
      
    } catch (error) {
      log('刷新失败:', error)
      Taro.showToast({
        title: '刷新失败',
        icon: 'error',
        duration: 1500
      })
    } finally {
      setRefreshing(false)
    }
  }, [onRefresh, lastRefreshTime, minInterval])
  
  return { 
    refreshing, 
    handleRefresh,
    lastRefreshTime
  }
}
